import { ethers } from 'ethers';

// 声明全局的 ethereum 类型
declare global {
  interface Window {
    ethereum?: any;
  }
}

// 检查是否安装钱包
export const isWalletInstalled = () => {
  return typeof window.ethereum !== 'undefined';
};

// 连接钱包
export const connectWallet = async () => {
  try {
    if (!isWalletInstalled()) {
      throw new Error('请安装MetaMask钱包');
    }

    // 请求账户访问权限
    const accounts = await window.ethereum.request({
      method: 'eth_requestAccounts'
    });

    // 获取默认账户
    const account = accounts[0];
    
    // 获取网络信息
    const provider = new ethers.BrowserProvider(window.ethereum);
    const network = await provider.getNetwork();

    return {
      account,
      network
    };
  } catch (error) {
    console.error('连接钱包失败:', error);
    throw error;
  }
};
